package com.spzx.user.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.HttpUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.ValidatorUtil;
import com.spzx.user.domain.UserInfo;
import com.spzx.user.service.IUserInfoService;
import com.spzx.user.service.SmsService;
import jakarta.annotation.Resource;
import org.apache.http.HttpResponse;
import org.joda.time.DateTime;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    IUserInfoService userInfoService;

    @Resource
    StringRedisTemplate stringRedisTemplate;


    @Override
    public int sendCode(String phone) {
        //1、校验手机号码格式

        boolean mobile = ValidatorUtil.isMobile(phone);

        if (!mobile){
            throw new ServiceException("手机号码格式有误");
        }
        //2、校验手机号 是否被注册

        UserInfo userInfoFlag = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));

        if (!ObjectUtils.isEmpty(userInfoFlag)){
            throw new ServiceException("手机号被注册了");
        }

        //3、校验手机号获取验证吗的频率 （一天只能获取5 次 ，2分中内不可重复发送）
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("spzx:user:code:lock:" + phone, "1", 2, TimeUnit.MINUTES);

        if (!flag){
            throw new ServiceException("2分钟内不可重复发送");
        }
        String countKey = "spzx:user:code:lock:"+phone;
        String s = stringRedisTemplate.opsForValue().get(countKey);
        if (StringUtils.hasText(s)&&Integer.parseInt(s)>=5){
            throw new ServiceException("验证码发送异常 （达到每日发送上线）");
        }

        //4、发送验证码：调用第三方短信API发送
        //设置验证码 用hutool工具
        String code = RandomUtil.randomNumbers(4);

        //将验证码存到redis
        int timeout =30;
        String codeKey = "spzx:user:code:code:"+phone;
        stringRedisTemplate.opsForValue().set(codeKey,code,timeout,TimeUnit.MINUTES);

        //更新当前手机号验证码的发送频率 一天至多发送5次 基于之前+1  第一次发送验证码 设置过期时间为24小时
        Long limit = stringRedisTemplate.opsForValue().increment(countKey);

        if (limit==1L){
          stringRedisTemplate.expire(countKey, new DateTime().plusDays(1)
                  .withTimeAtStartOfDay()
                  .getMillis() - System.currentTimeMillis()
                  , TimeUnit.MILLISECONDS);
        }

        //调用第三方服务发送验证码
        senMsg(code,phone);




        return 1;
    }


    //使用的是三网短信  中的api复制
    private void senMsg(String code , String phone){
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "0c000bccbc5f4f5fb0e9cce65bdad9df";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "code:"+code);
        bodys.put("template_id", "CST_ptdie100");  //注意，CST_ptdie100该模板ID仅为调试使用，调试结果为"status": "OK" ，即表示接口调用成功，然后联系客服报备自己的专属签名模板ID，以保证短信稳定下发
        bodys.put("phone_number", phone);


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
